import axios from "axios";
import {ElMessage} from "element-plus";
import router from "@/router/index.js";

const request = axios.create({
  baseURL: "http://127.0.0.1:8080",
  timeout: 5000,
})

request.interceptors.request.use(config => {
  config.headers['Content-Type'] = 'application/json;charset=UTF-8';
  let user = JSON.parse(localStorage.getItem("code_user") || '{}');
  // console.log(user);
  config.headers['token'] = user.token;
  return config;
}, error => {
  return Promise.reject(error);
})

request.interceptors.response.use(response => {
  let res = response.data;
  if (typeof res === 'string') {
    res = res ? JSON.parse(res) : res
  }
  if (res.code === 401) {
    ElMessage.error(res.msg);
    router.push('/login');
  } else {
    return res;
  }
}, error => {
  if (error.response.status === 404) {
    ElMessage('未找到请求接口')
  } else if (error.response.status === 500) {
    ElMessage('系统异常，请联系管理员，自行查看报错')
  } else {
    console.log(error.message)
  }
  return Promise.reject(error);
})
export default request;
